<?php

namespace App\Jobs;

use App\Models\BookOrder;
use App\Models\BookRule;
use App\Models\BookRulePrice;
use App\Models\SettleOrderLog;
use App\Services\BookOrderService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class BookRuleSettle implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $bookRule;

    /**
     * BookRuleSettle constructor.
     * @param BookRule $bookRule
     */
    public function __construct(BookRule $bookRule)
    {
        $this->bookRule = $bookRule;
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        $startTime = microtime(true);

        DB::beginTransaction();
        try {
            $bookRule = $this->bookRule;
            // 标记此订餐规则为已结算
            $bookRule->is_settled = BookRule::SETTLED;
            $bookRule->save();
            // 此订餐规则的条目总价
            $totalPrice = BookRulePrice::where('rule_id', $bookRule->id)->sum('total_price');
            // 此订餐规则下的订单数，所有非已取消, 能结算的订单
            $orderCount = BookOrder::where('book_rule_id', $bookRule->id)->isNotCanceled()->canSettle()->count();
            // 订单原价
            $originPrice = (float)bcdiv($totalPrice, $orderCount, 2);
            // 结算此订餐规则下的所有非已取消, 能结算的订单
            $bookOrder = BookOrder::where('book_rule_id', $bookRule->id)->isNotCanceled()->canSettle()->with('user.role')->get();
            foreach ($bookOrder as $item) {
                BookOrderService::settle($item, $originPrice, $bookRule->eat_type);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw $exception;
        }

        $endTime = microtime(true);

        $settleOrderLog = new SettleOrderLog();
        $settleOrderLog->book_rule_id = $bookRule->id;
        $settleOrderLog->count = $orderCount;
        $settleOrderLog->excute_time = round($endTime - $startTime, 3);
        $settleOrderLog->save();

    }
}
